<?php
namespace app\store\model;
use app\common\model\Category as CategoryModel;
use think\Cache;

/**
 * 菜品分类模型
 */
class Category extends CategoryModel
{
    /**
     * 添加新记录
     */
    public function add($data,$shop_id)
    {
		$data['shop_id'] = $shop_id;
        $data['wxapp_id'] = self::$wxapp_id;
        $this->deleteCache($shop_id);
        return $this->allowField(true)->save($data);
    }

    /**
     * 编辑记录
     */
    public function edit($data,$shop_id)
    {
        $this->deleteCache($shop_id);
        return $this->allowField(true)->save($data);
    }

    /**
     * 删除分类
     */
    public function remove($category_id,$shop_id)
    {
        // 判断是否存在菜品
        if ($goodsCount = (new Goods)->where(['category_id'=>$category_id,'shop_id'=>$shop_id])->count()) {
			$this->error = '该分类下存在' . $goodsCount . '个菜品，不允许删除';
            return false;
        }
        // 判断是否存在子分类
        if ((new self)->where(['parent_id' => $category_id])->count()) {
			$this->error = '该分类下存在子分类，请先删除';
            return false;
        }
        $this->deleteCache($shop_id);
        return $this->delete();
    }

    /**
     * 删除缓存
     */
    private function deleteCache($shop_id)
    {
        return Cache::rm('category_' . self::$wxapp_id . '_' . $shop_id);
    }

}
